﻿@{
    ViewBag.Title = "多文档翻译工具";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style>
    body {
        background-color: #f2f2f2;
        font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    }

    .container {
        max-width: 800px;
        margin: 30px auto;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 25px;
    }

    .header {
        text-align: center;
        margin-bottom: 30px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
    }

        .header h2 {
            color: #1E9FFF;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 16px;
        }

    .upload-section {
        margin-bottom: 25px;
        text-align: center;
    }

    .file-list {
        background: #f8f8f8;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 20px;
        min-height: 100px;
        max-height: 300px;
        overflow-y: auto;
    }

    .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        margin-bottom: 8px;
        background: #fff;
        border-radius: 4px;
        border-left: 3px solid #1E9FFF;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .file-name {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .file-size {
        color: #888;
        font-size: 12px;
        margin-left: 10px;
    }

    .file-status {
        margin-left: 15px;
        font-size: 12px;
        padding: 2px 8px;
        border-radius: 10px;
    }

    .status-waiting {
        background: #f0f0f0;
        color: #888;
    }

    .status-uploading {
        background: #e6f7ff;
        color: #1890ff;
    }

    .status-completed {
        background: #f6ffed;
        color: #52c41a;
    }

    .progress-section {
        margin-bottom: 25px;
    }

    .result-section {
        text-align: center;
        padding: 20px;
        background: #f8f8f8;
        border-radius: 4px;
        display: none;
    }

        .result-section h3 {
            color: #52c41a;
            margin-bottom: 15px;
        }

    .download-btn {
        margin: 15px 5px;
    }

    .footer {
        text-align: center;
        margin-top: 10px;
        color: #999;
        font-size: 12px;
    }

    .layui-progress {
        margin-bottom: 10px;
    }

    .progress-text {
        text-align: center;
        font-size: 14px;
        color: #666;
        margin-bottom: 15px;
    }

    .remove-file {
        color: #ff4d4f;
        cursor: pointer;
        margin-left: 10px;
    }

    .signalr-status {
        text-align: center;
        padding: 8px;
        margin-bottom: 15px;
        border-radius: 4px;
        font-size: 14px;
    }

    .signalr-connected {
        background: #f6ffed;
        color: #52c41a;
        border: 1px solid #b7eb8f;
    }

    .signalr-connecting {
        background: #e6f7ff;
        color: #1890ff;
        border: 1px solid #91d5ff;
    }

    .signalr-disconnected {
        background: #fff2f0;
        color: #ff4d4f;
        border: 1px solid #ffccc7;
    }

    
    .file-progress {
        width: 60px;
        font-size: 12px;
        color: #888;
        margin-left: 10px;
    }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.0/signalr.min.js"></script>

<div class="container">
    <div class="header">
        <h2>多文档翻译工具</h2>
        <p>上传多个Word文档，使用AI进行批量翻译并保持原格式</p>
    </div>


@*     <div class="signalr-status signalr-connecting" id="signalrStatus">
        <i class="layui-icon">&#xe63d;</i> 正在连接到服务器...
    </div> *@

    <div class="upload-section">
        <button type="button" class="layui-btn layui-btn-normal" id="selectFiles">
            <i class="layui-icon">&#xe67c;</i>选择Word文档
        </button>
        <button type="button" class="layui-btn" id="uploadFiles">
            <i class="layui-icon">&#xe681;</i>开始翻译
        </button>
        <button type="button" class="layui-btn layui-btn-primary" id="clearFiles">
            <i class="layui-icon">&#x1006;</i>清空列表
        </button>
    </div>

    <div class="file-list" id="fileList">
        <div class="layui-fluid" style="text-align: center; padding: 30px; color: #999;">
            <i class="layui-icon" style="font-size: 40px;">&#xe63f;</i>
            <p>暂无文件，请点击上方按钮添加Word文档</p>
        </div>
    </div>

    <div class="progress-section">
        <div class="progress-text" id="progressText">等待翻译...</div>
        <div class="layui-progress layui-progress-big" lay-filter="totalProgress" id="totalProgress">
            <div class="layui-progress-bar" lay-percent="0%"></div>
        </div>
    </div>

    <div class="result-section" id="resultSection">
        <h3><i class="layui-icon" style="color: #52c41a;">&#xe605;</i> 翻译完成！</h3>
        <p>已成功翻译所有文档，点击下方按钮下载</p>
        <button type="button" class="layui-btn layui-btn-normal download-btn" id="downloadAll">
            <i class="layui-icon">&#xe601;</i> 下载所有文档
        </button>
        <button type="button" class="layui-btn layui-btn-primary download-btn" id="newTranslation">
            <i class="layui-icon">&#xe669;</i> 新的翻译
        </button>
    </div>

    <div class="footer">
        <p>支持格式: .docx | 最大文件: 10MB | 最大数量: 10个</p>
    </div>
</div>

@section Scripts {
    <script>
        layui.use(['upload', 'element', 'layer'], function () {
            var upload = layui.upload;
            var element = layui.element;
            var layer = layui.layer;
            var $ = layui.$;

            // 已选择的文件
            var selectedFiles = [];
            var connection = null;
            var connectionId = null;
            var translatedFiles = [];
            var currentProcessingFile = '';

            var totalFiles = 0;
            var fileProgress = {};

            // SignalR初始化
            function initSignalRConnection() {
                connection = new signalR.HubConnectionBuilder()
                    .withUrl('/translationHub')
                    .configureLogging(signalR.LogLevel.Information)
                    .build();

                // 监听进度更新
                connection.on('UpdateProgress', function (filecompleted, filetotal, grandcompleted, grandtotal, currentFile, status) {
                    updateProgress(filecompleted, filetotal, grandcompleted, grandtotal, currentFile, status);
                });

                connection.on('TranslationComplete', function (fileUrls) {
                    onTranslationComplete(fileUrls);
                });

                connection.on('TranslationError', function (errorMessage) {
                    onTranslationError(errorMessage);
                });

                connection.start()
                    .then(function () {
                        connectionId = connection.connectionId;
                        console.log('SignalR连接成功，ConnectionId:', connectionId);
                    })
                    .catch(function (err) {
                        console.error('SignalR连接失败:', err);
                    });
            }

            // 更新进度条
            function updateProgress(filecompleted, filetotal, grandcompleted, grandtotal, currentFile, status) {
                // 更新总进度条
                var percent = filetotal > 0 ? Math.round((grandcompleted / grandtotal) * 100) : 0;
                element.progress('totalProgress', percent + '%');

                // 更新进度文本
                if (currentFile && currentFile !== currentProcessingFile) {
                    currentProcessingFile = currentFile;
                }

                var progressText = status || `处理中: ${filecompleted}/${filetotal}`;
                if (currentProcessingFile) {
                    progressText = `${currentProcessingFile} - ${progressText}`;
                }
                $('#progressText').text(progressText);

                // 文件级别的进度，更新文件状态
                if (status && status.includes('处理中:')) {
                    var fileNameMatch = status.match(/处理中: (.+?) \(/);
                    if (fileNameMatch && fileNameMatch[1]) {
                        updateFileStatus(fileNameMatch[1], 'processing', filecompleted, filetotal);
                    }
                } else if (status && status.includes('已完成:')) {
                    var fileNameMatch = status.match(/已完成: (.+)/);
                    if (fileNameMatch && fileNameMatch[1]) {
                        updateFileStatus(fileNameMatch[1], 'completed');
                    }
                }

            }


            // 更新文件状态
            function updateFileStatus(fileName, status, processed, total) {
                $('.file-item').each(function () {
                    var nameElement = $(this).find('.file-name');
                    if (nameElement.text() === fileName) {
                        var statusElement = $(this).find('.file-status');
                        var progressElement = $(this).find('.file-progress');

                        if (!progressElement.length) {
                            progressElement = $('<span class="file-progress"></span>');
                            statusElement.after(progressElement);
                        }

                        switch (status) {
                            case 'processing':
                                statusElement
                                    .removeClass('status-waiting status-completed')
                                    .addClass('status-uploading')
                                    .text('翻译中');
                                progressElement.text(`(${processed}/${total})`);
                                break;
                            case 'completed':
                                statusElement
                                    .removeClass('status-waiting status-uploading')
                                    .addClass('status-completed')
                                    .text('翻译完成');
                                progressElement.text('');
                                break;
                        }
                    }
                });
            }


            // 翻译完成
            function onTranslationComplete(fileUrls) {
                $('#progressText').text('所有文件翻译完成!');
                element.progress('totalProgress', '100%');
                $('#resultSection').show();

                // 显示下载链接
                var downloadLinksHtml = '<p>下载链接：</p>';
                fileUrls.forEach(function (url, index) {
                    var fileName = url.split('/').pop().replace('_translated', '');
                    downloadLinksHtml += `<a href="${url}" class="layui-btn layui-btn-xs layui-btn-primary" download>${fileName}</a> `;
                });
                $('#downloadLinks').html(downloadLinksHtml);

                translatedFiles = fileUrls;
            }

            // 翻译错误处理
            function onTranslationError(errorMessage) {
                layer.msg('翻译过程中出现错误: ' + errorMessage, { icon: 2 });
                $('#progressText').text('翻译失败，请重试。');
                element.progress('totalProgress', '0%');
            }


            var uploadInst = upload.render({
                elem: '#selectFiles',
                elemList: $('#fileList'),
                url: '/Translation/UploadDocuments', 
                multiple: true,
                unified:true,
                // 限制的文件类型
                accept: 'file',
                exts: 'docx',
                // 限制文件大小，10MB
                size: 10 * 1024, 
                auto: false,
                bindAction: '#uploadFiles',
                data: {
                    connectionId: function () {
                        return connectionId;
                    }
                },
                // 点击选择文件后触发
                choose: function (obj) {
                    // 选中的文件
                    var files = obj.pushFile();

                    totalFiles = this.files ? Object.keys(this.files).length : 0;
                    fileProgress = {};

                    // 把提示文字清空掉，写在这里能够在追加文件时fileList不被清空
                    if (selectedFiles.length === 0) {
                        $('#fileList').html('');
                    }

                    // 读取本地文件列表
                    obj.preview(function (index, file, result) {
                        // 不允许添加重复文件
                        if (selectedFiles.some(f => f.name === file.name)) {
                            layer.msg('文件 ' + file.name + ' 已存在', { icon: 2 });
                            return;
                        }

                        file.layIndex = index;
                        selectedFiles.push(file);
                        var fileSize = (file.size / 1024 / 1024).toFixed(2) + ' MB';

                        var fileItem = $(
                            '<div class="file-item" data-index="' + index + '">' +
                            '<div class="file-name">' + file.name + '</div>' +
                            '<div class="file-size">' + fileSize + '</div>' +
                            '<div class="file-status status-waiting">等待翻译</div>' +
                            '<div class="remove-file"><i class="layui-icon">&#x1006;</i></div>' +
                            '</div>'
                        );

                        $('#fileList').append(fileItem);

                        // 根据lay-index移除文件
                        fileItem.find('.remove-file').click(function () {
                            var removeIndex = $(this).parent().data('lay-index');
                            selectedFiles = selectedFiles.filter((f, i) => i !== removeIndex);
                            $(this).parent().remove();

                            if (selectedFiles.length === 0) {
                                $('#fileList').html(
                                    '<div class="layui-fluid" style="text-align: center; padding: 30px; color: #999;">' +
                                    '<i class="layui-icon" style="font-size: 40px;">&#xe63f;</i>' +
                                    '<p>暂无文件，请点击上方按钮添加Word文档</p>' +
                                    '</div>'
                                );
                            }
                        });
                    });
                },
                // 开始翻译前的回调
                before: function (obj) {
                    console.log('before 回调被触发');
                    console.log(selectedFiles)

                    if (!connectionId) {
                        layer.msg('请等待服务器连接完成', { icon: 2 });
                        return false;
                    }

                    // 更新所有文件状态为上传中
                    $('.file-status').removeClass('status-waiting status-completed').addClass('status-uploading').text('上传中...');
                    $('#progressText').text('开始上传...');

                    // 进度条
                    element.progress('totalProgress', '0%');

                    $('#resultSection').hide();
                    return true;
                },
                progress: function (n, elem, file, index) {
                    var percent = Math.floor(n) + '%';
                    var fileItem = $('.file-item').eq(index);
                    fileItem.find('.file-status').text('上传中 ' + percent);
                },

                allDone: function (obj) {
                    console.log('所有文件上传完成');
                    $('#progressText').text('上传完成，开始翻译...');

                    // 把所有文件统一改为“上传完成”
                    $('.file-status')
                        .removeClass('status-uploading')
                        .addClass('status-completed')
                        .text('上传完成');
                },
                done: function (res, index, upload) {
                    if (!res.success) {
                        $('.file-item').eq(index).find('.file-status')
                            .removeClass('status-uploading')
                            .text('上传失败');
                        layer.msg(res.message || '文件上传失败', { icon: 2 });
                    }
                },
                error: function (index, upload) {
                    // 上传失败回调
                    $('.file-item').eq(index).find('.file-status')
                        .removeClass('status-uploading')
                        .text('上传失败');
                    layer.msg('文件上传失败', { icon: 2 });
                }
            });




            $(document).ready(function () {
                initSignalRConnection();
            });


            // 绑定上传按钮
            $('#uploadFiles').click(function () {
                if (selectedFiles.length === 0) {
                    layer.msg('请先选择文件', { icon: 2 });
                    return false;
                }
                if (!connectionId) {
                    layer.msg('正在连接服务器，请稍后...', { icon: 2 });
                    return false;
                }
            });

            // 清空文件列表
            $('#clearFiles').click(function () {
                selectedFiles = [];
                translatedFiles = [];
                currentProcessingFile = '';
                $('#fileList').html(
                    '<div class="layui-fluid" style="text-align: center; padding: 30px; color: #999;">' +
                    '<i class="layui-icon" style="font-size: 40px;">&#xe63f;</i>' +
                    '<p>暂无文件，请点击上方按钮添加Word文档</p>' +
                    '</div>'
                );
                element.progress('totalProgress', '0%');
                $('#progressText').text('等待翻译...');
                $('#resultSection').hide();
                $('#downloadLinks').empty();
            });

            // 开始新的翻译
            $('#newTranslation').click(function () {
                $('#clearFiles').click();
            });

            // 下载所有文档
            $('#downloadAll').click(function () {
                if (translatedFiles.length === 0) {
                    layer.msg('没有可下载的文件', { icon: 2 });
                    return;
                }

                // 逐个下载文件
                translatedFiles.forEach(function (url) {
                    var link = document.createElement('a');
                    link.href = url;
                    link.download = url.split('/').pop();
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                });
            });



        });
    </script>
}